package gee

import (
	"net/http"
)

type HandlerFunc func(c *Context)

type Engine struct {
	router *router
}

func New() *Engine {
	return &Engine{router: newRouter()}
}

func (e *Engine) addRoute(method string, pattern string, Handler HandlerFunc) {
	e.router.addRoute(method, pattern, Handler)
}

func (e *Engine) GET(pattern string, Handler HandlerFunc) {
	e.addRoute("GET", pattern, Handler)
}

func (e *Engine) POST(pattern string, Handler HandlerFunc) {
	e.addRoute("POST", pattern, Handler)
}

func (e *Engine) Run(addr string) (err error) {
	// Engine类实现了ServeHTTP接口函数，http请求会自动被这个函数处理
	return http.ListenAndServe(addr, e)
}

// 这是个必须实现的接口，也就是如何处理输入的http请求写入response中
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 对于每个新的请求要创建新的上下文context
	c := newContext(w, r)
	e.router.handle(c)
}
